package com.eostoken.eos_wallet.ui.fragment;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.FragmentUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.MapUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.eostoken.eos_wallet.R;
import com.eostoken.eos_wallet.base.BaseFragment;
import com.eostoken.eos_wallet.bean.MiningOrderIncomeItem;
import com.eostoken.eos_wallet.bean.MyOrderListBean;
import com.eostoken.eos_wallet.bean.PageInfo;
import com.eostoken.eos_wallet.bean.WithdrawIndexBean;
import com.eostoken.eos_wallet.db.MgpWallet;
import com.eostoken.eos_wallet.mvp.mode.AppsModel;
import com.eostoken.eos_wallet.mvp.presenter.AppsPresenterImpl;
import com.eostoken.eos_wallet.mvp.view.AppsView;
import com.eostoken.eos_wallet.ui.adapter.MinerIncomeAdapter;
import com.eostoken.eos_wallet.ui.fragmentfactory.FragmentFactory;
import com.eostoken.eos_wallet.utils.RSAUtils;
import com.eostoken.eos_wallet.utils.WalletUtils;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.pullLayout.QMUIPullLayout;

import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static com.eostoken.eos_wallet.utils.Constants.BACKUP_MNEMONIC;
import static com.eostoken.eos_wallet.utils.Constants.CONFIRM_MNEMONIC;
import static com.eostoken.eos_wallet.utils.Constants.MINING_INDEX;
import static com.eostoken.eos_wallet.utils.Constants.MY_ORDER;
import static com.eostoken.eos_wallet.utils.Constants.MY_STIMULATE;
import static com.eostoken.eos_wallet.utils.Constants.WITHD_RAW_INDEX;

public class StimulateListFragment extends BaseFragment<AppsModel, AppsView, AppsPresenterImpl> implements AppsView {

    @BindView(R.id.incomeTv)
    AppCompatTextView incomeTv;
    @BindView(R.id.topBar)
    QMUITopBarLayout topBar;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;

    private static final String moneyType = "2";
    private MinerIncomeAdapter minerIncomeAdapter;
    private int limit = 50;
    private String accountName;
    private MgpWallet wallet;
    private boolean isLoadMore = true;
    private PageInfo pageInfo = new PageInfo();
    private List<MiningOrderIncomeItem> myOrderListBeanList;
    private MyOrderListBean myOrderListBean;
    private String money = "0.0000";
    private WithdrawIndexBean withdrawIndexBean;

//    private static class LazyHolder {
//        private static final StimulateListFragment INSTANCE = new StimulateListFragment();
//    }
//
//    public static final StimulateListFragment getInstance() {
//        return LazyHolder.INSTANCE;
//    }

    @Override
    protected int getContentLayout() {
        return R.layout.fragment_stimulate_list;
    }

    @Override
    protected void initData() {
        wallet = WalletUtils.getCurrentWallet(getActivity());
        accountName = wallet.getCurrentAccountName();
    }

    @Override
    protected void initView(View contentView) {
        topBar.setTitle(StringUtils.getString(R.string.str_my_motivation));
        topBar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popOrFinish();
            }
        });
        topBar.addRightTextButton(StringUtils.getString(R.string.str_mining_index), R.id.topbar_right_change_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Fragment fragment = FragmentFactory.getInstatic().getFragment(MINING_INDEX);
                FragmentUtils.replace(getFragmentManager(), fragment, R.id.frag_container, "MiningIndexFragment", true);

            }
        });

        minerIncomeAdapter = new MinerIncomeAdapter();
        minerIncomeAdapter.setAnimationEnable(true);
        minerIncomeAdapter.setEmptyView(getLayoutInflater().inflate(R.layout.view_empty, null, false));
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
        recyclerView.setAdapter(minerIncomeAdapter);
        initLoadMore();
        incomeTv.setText(money);  // 进入页面，刷新数据
        swipeLayout.setRefreshing(true);
        refresh();
    }

    /**
     * 初始化加载更多
     */
    private void initLoadMore() {
        swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });
        minerIncomeAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                getMyOrderWallet();
            }
        });
        minerIncomeAdapter.getLoadMoreModule().setAutoLoadMore(true);
        //当自动加载开启，同时数据不满一屏时，是否继续执行自动加载更多(默认为true)
        minerIncomeAdapter.getLoadMoreModule().setEnableLoadMoreIfNotFullPage(false);
    }

    /**
     * 刷新
     */
    private void refresh() {
        isLoadMore = false;
        // 这里的作用是防止下拉刷新的时候还可以上拉加载
        minerIncomeAdapter.getLoadMoreModule().setEnableLoadMore(false);
        minerIncomeAdapter.setList(null);
        // 下拉刷新，需要重置页数
        pageInfo.reset();
        getMyOrderWallet();
    }

    public void getMyOrderWallet() {
        try {
            Map params = MapUtils.newHashMap();
            params.put("address", accountName);
            params.put("limit", limit + "");
            params.put("page", pageInfo.page + "");
            String jsonData = GsonUtils.toJson(params);
            String content = RSAUtils.encrypt(jsonData);
            presenter.requestPortData(content, MY_ORDER);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void getWithdrawIndex() {
        try {
            Map params = MapUtils.newHashMap();
            params.put("address", accountName);
            params.put("moneyType", moneyType);
            String jsonData = GsonUtils.toJson(params);
            String content = RSAUtils.encrypt(jsonData);
            presenter.requestPortData(content, WITHD_RAW_INDEX);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick(R.id.nextstepBtn)
    public void onViewClicked() {
        Bundle bundle = new Bundle();
        bundle.putString("moneyType", moneyType);
        Fragment fragment = FragmentFactory.getInstatic().getFragment(MY_STIMULATE);
        fragment.setArguments(bundle);
        FragmentUtils.replace(getFragmentManager(), fragment, R.id.frag_container, "ExtractionYieldFragment", true);

    }

    @Override
    public void updateView(Object data, int responseSuccessCode) {
        switch (responseSuccessCode) {
            case MY_ORDER:
                swipeLayout.setRefreshing(false);
                minerIncomeAdapter.getLoadMoreModule().setEnableLoadMore(true);
                if (data != null) {
                    myOrderListBean = GsonUtils.fromJson(data.toString(), MyOrderListBean.class);
                    if (myOrderListBean != null) {
                        if (myOrderListBean.getCode() == 0) {
                            MyOrderListBean.DataBean dataBean = myOrderListBean.getData();
                            if (dataBean != null) {
                                myOrderListBeanList = dataBean.getList();
                                money = dataBean.getMoney();
                                if (!ObjectUtils.isEmpty(myOrderListBeanList)) {
                                    if (pageInfo.isFirstPage()) {
                                        //如果是加载的第一页数据，用 setData()
                                        minerIncomeAdapter.setList(myOrderListBeanList);
                                    } else {
                                        //不是第一页，则用add
                                        minerIncomeAdapter.addData(myOrderListBeanList);
                                    }
                                }
                            }
                        } else {
                            ToastUtils.showShort(myOrderListBean.getMsg());
                        }
                    }
                }
                if (!ObjectUtils.isEmpty(myOrderListBeanList)) {
                    if (myOrderListBeanList.size() < limit) {
                        //如果不够一页,显示没有更多数据布局
                        minerIncomeAdapter.getLoadMoreModule().loadMoreEnd();
                    } else {
                        minerIncomeAdapter.getLoadMoreModule().loadMoreComplete();
                    }
                } else {
                    minerIncomeAdapter.getLoadMoreModule().loadMoreEnd();
                }
                pageInfo.nextPage();
                break;
            case WITHD_RAW_INDEX:
                if (data != null) {
                    withdrawIndexBean = GsonUtils.fromJson(data.toString(), WithdrawIndexBean.class);
                    if (withdrawIndexBean != null) {
                        if (withdrawIndexBean.getCode() == 0) {
                            WithdrawIndexBean.DataBean dataBean = withdrawIndexBean.getData();
                            if (dataBean != null) {
                                money = dataBean.getMoney();
                                incomeTv.setText(money);
                            }
                        } else {
                            ToastUtils.showShort(withdrawIndexBean.getMsg());
                        }
                    }
                }
                break;
        }
    }

    @Override
    public void onFailure(Object data, int responseFailCode) {
        switch (responseFailCode) {
            case MY_ORDER:
                swipeLayout.setRefreshing(false);
                minerIncomeAdapter.getLoadMoreModule().setEnableLoadMore(true);
                minerIncomeAdapter.getLoadMoreModule().loadMoreFail();
                break;
            case WITHD_RAW_INDEX:
                break;
        }
    }

    @Override
    public void updateView(boolean success, Object o1, Object o2) {

    }

    @Override
    public AppsModel createModel() {
        return new AppsModel();
    }

    @Override
    public AppsView createView() {
        return this;
    }

    @Override
    public AppsPresenterImpl createPresenter() {
        return new AppsPresenterImpl(getActivity());
    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void onStop() {
        super.onStop();
        pageInfo.reset();
    }

    @Override
    public void onResume() {
        super.onResume();
        getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        BarUtils.setStatusBarColor(getActivity(), ContextCompat.getColor(getActivity(), R.color.qmui_config_color_transparent));
        getWithdrawIndex();
    }
}
